<?php

namespace App\Models\video;

use App\Http\Config\ErrorCode;
use App\Library\UpTools;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

// up用户表
class BroadcasterModel extends Model
{
    protected $table = "up_broadcaster"; //表名
    const CREATED_AT = null;
    const UPDATED_AT = null;

    public static function transferField($data){
        if(!$data){
            return [];
        }
        $data = UpTools::transferFields($data);
        if(isset($data[0])){
            foreach ($data as $k => $item){
                if(array_key_exists('registerTime', $item)){
                    $data[$k]["registerTime"] = date("Y-m-d H:i", $item["registerTime"]);
                }
                if(array_key_exists('bgImageId', $item)){
                    $data[$k]["bgImageUrl"] = UpTools::processingPictures($item["bgImageId"]);
                }
                if(array_key_exists('avatarId', $item)){
                    $data[$k]["avatarUrl"] = UpTools::processingPictures($item["avatarId"]);
                }
                if(array_key_exists('status', $item)){
                    $data[$k]["statusText"] = $item["status"] == '1' ? "正常" : "禁用";
                }
            }
        }else{
            if(array_key_exists("registerTime", $data)){
                $data["registerTime"] = date("Y-m-d H:i", $data["registerTime"]);
            }
            if(array_key_exists("bgImageId", $data)){
                $data["bgImageUrl"] = UpTools::processingPictures($data["bgImageId"]);
            }
            if(array_key_exists("avatarId", $data)){
                $data["avatarUrl"] = UpTools::processingPictures($data["avatarId"]);
            }
            if(array_key_exists('status', $data)){
                $data["statusText"] = $data["status"] == '1' ? "正常" : "禁用";
            }
        }
        return $data;
    }

    public function relation(){
        return $this->hasMany(BroadcasterRelationModel::class,'broadcaster_id','id');
    }

    //分页获取所有字段数据
    public static function getList($field = '*', $filter = [], $page = 1, $limit = 10, $order = "register_time", $sort = "desc"){
        $db = self::query()->where($filter)->select(is_array($field) ? $field : explode(",", $field));
        $data['count'] = $db->count();
        $data['currentPage'] = $page;
        $data['totalPage'] = ceil(($data['count'])/$limit);
        $data['list'] = $db->skip(($page - 1) * $limit)->take($limit)->orderBy($order, $sort)->get();
        if($data['list']){
            $data['list'] = self::transferField($data['list']->toArray());
        }
        return $data;
    }

    //根据条件获取数量
    public static function getCount($filter){
        if(!empty($filter)){
            return self::query()->where($filter)->count();
        }else{
            return self::query()->count();
        }
    }

    //添加
    public static function add($data, $getId=false){
        if(!$data)
            return true;
        try {
            $data["mall_id"] = request()->mallData["id"];
            if(empty($data["register_time"])) $data["register_time"] = time();
            if ($getId) {
                $id = self::query()->insertGetId($data);
                return $id;
            } else {
                return self::query()->insert($data);
            }
        }catch (\Exception $e){
            return ErrorCode::code("customized", $e->getMessage());
        }
    }

    //更新
    public static function doUpdate($data, $filter = []){
        $res = self::query()->where($filter)->update($data);
        if($res || $res === 0){
            return true;
        }else{
            return false;
        }
    }

    //获取某字段的值
    public static function getValue($field, $filter = []){
        if(!is_array($field)){
            return self::query()->where($filter)->value($field);
        }
        return false;
    }

    //获取多字段数据
    public static function getFields($field, $filter = [], $one = true, $toArray = true){ //缓存方法：缓存所有字段，只返回需要的字段
        if($one){
            $data = self::query()->where($filter)->select(is_array($field) ? $field : explode(",", $field))->first();
            return $data ? ($toArray ? self::transferField($data->toArray()) : UpTools::transferFields($data->toArray())) : [];
        }else{
            $data = self::query()->where($filter)->select(is_array($field) ? $field : explode(",", $field))->get()->toArray();
            return $data ? ($toArray ? self::transferField($data) : UpTools::transferFields($data)) : [];
        }
    }

    //根据ID删除数据
    public static function delById($id){
        $data = self::from(self::query()->getModel()->getTable()." as b")
            ->leftJoin(BroadcasterRelationModel::query()->getModel()->getTable()." as br", "b.id", "=", "br.broadcaster_id")
            ->select("br.user_id", "br.openid")
            ->where(["b.id" => $id])
            ->get();
        $result = self::query()->where('id', $id)->delete();
        if($result){
            $temp = SubscriptionModel::getFields("id", ["broadcaster_id" => $id], false, false);
            foreach ($temp as $item){
                SubscriptionModel::delById($item["id"]);
            }
            VodVideoModel::delByFilter(["broadcaster_id" => $id]);
            BroadcasterRelationModel::delByFilter(["broadcaster_id" => $id]);
            foreach ($data as $item) {
                VideoUserModel::doUpdate(["user_type" => 0], ["id" => $item["user_id"]]);
                DB::table("member")->where("up_openid", $item["openid"])->update(["up_openid" => null, "user_type" => 0]);
            }
        }
        return $result;
    }
}